use std::sync::Arc;
use tokio::sync::Mutex;
use serde::{Deserialize, Serialize};
use crate::utils::message_queue::MessageQueue; 

#[derive(Debug, Serialize, Deserialize)]
pub struct RealTimeData {
    pub data_type: String,
    pub timestamp: i64,
    pub content: serde_json::Value,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct StockPriceUpdate {
    pub code: String,
    pub name: String,
    pub price: f64,
    pub change: f64,
    pub change_percent: f64,
    pub volume: i64,
    pub timestamp: i64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct MarketIndexUpdate {
    pub code: String,
    pub name: String,
    pub value: f64,
    pub change: f64,
    pub change_percent: f64,
    pub timestamp: i64,
}

pub struct RealTimeService {
    message_queue: Arc<Mutex<MessageQueue>>,
    data_dao: DataItemDao,
}

impl RealTimeService {
    pub fn new(message_queue: Arc<Mutex<MessageQueue>>) -> Self {
        Self {
            message_queue,
            data_dao: DataItemDao::new(),
        }
    }

    // 处理实时数据
    pub async fn process_real_time_data(&self, data: RealTimeData) -> Result<(), String> {
        // 根据数据类型进行不同处理
        match data.data_type.as_str() {
            "stock_price" => self.process_stock_price(data).await,
            "market_index" => self.process_market_index(data).await,
            "trading_signal" => self.process_trading_signal(data).await,
            "system_notification" => self.process_system_notification(data).await,
            _ => Err(format!("Unknown data type: {}", data.data_type)),
        }
    }

    // 处理股票价格更新
    async fn process_stock_price(&self, data: RealTimeData) -> Result<(), String> {
        // 解析股票价格数据
        let stock_updates: Vec<StockPriceUpdate> = serde_json::from_value(data.content)
            .map_err(|e| format!("Failed to parse stock price data: {}", e))?;

        // 保存到数据库
        for update in &stock_updates {
            self.data_dao.save_stock_price(update)
                .map_err(|e| format!("Failed to save stock price: {}", e))?;
        }

        // 推送到消息队列
        let mut queue = self.message_queue.lock().await;
        queue.push_message("stock_prices".to_string(), serde_json::to_string(&stock_updates)
            .map_err(|e| format!("Failed to serialize stock updates: {}", e))?)
            .map_err(|e| e.to_string())?;

        Ok(())
    }

    // 处理市场指数更新
    async fn process_market_index(&self, data: RealTimeData) -> Result<(), String> {
        // 解析市场指数数据
        let index_updates: Vec<MarketIndexUpdate> = serde_json::from_value(data.content)
            .map_err(|e| format!("Failed to parse market index data: {}", e))?;

        // 保存到数据库
        for update in &index_updates {
            self.data_dao.save_market_index(update)
                .map_err(|e| format!("Failed to save market index: {}", e))?;
        }

        // 推送到消息队列
        let mut queue = self.message_queue.lock().await;
        queue.push_message("market_indices".to_string(), serde_json::to_string(&index_updates)
            .map_err(|e| format!("Failed to serialize index updates: {}", e))?)
            .map_err(|e| e.to_string())?;

        Ok(())
    }

    // 处理交易信号
    async fn process_trading_signal(&self, data: RealTimeData) -> Result<(), String> {
        // 推送到消息队列
        let mut queue = self.message_queue.lock().await;
        queue.push_message("trading_signals".to_string(), data.content.to_string())
            .map_err(|e| e.to_string())?;

        Ok(())
    }

    // 处理系统通知
    async fn process_system_notification(&self, data: RealTimeData) -> Result<(), String> {
        // 推送到消息队列
        let mut queue = self.message_queue.lock().await;
        queue.push_message("system_notifications".to_string(), data.content.to_string())
            .map_err(|e| e.to_string())?;

        Ok(())
    }

    // 获取最新的股票价格
    pub fn get_latest_stock_prices(&self, stock_codes: Vec<String>) -> Result<Vec<StockPriceUpdate>, String> {
        self.data_dao.get_latest_stock_prices(stock_codes)
            .map_err(|e| format!("Failed to get latest stock prices: {}", e))
    }

    // 获取最新的市场指数
    pub fn get_latest_market_indices(&self) -> Result<Vec<MarketIndexUpdate>, String> {
        self.data_dao.get_latest_market_indices()
            .map_err(|e| format!("Failed to get latest market indices: {}", e))
    }
}